package com.ruoyi.bbsAdmin.service.impl;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.bbsAdmin.domain.*;
import com.ruoyi.bbsAdmin.domain.vo.contentRedisVo;
import com.ruoyi.bbsAdmin.domain.vo.contentVo;
import com.ruoyi.bbsAdmin.domain.vo.treeSearchStructure;
import com.ruoyi.bbsAdmin.mapper.*;
import com.ruoyi.bbsAdmin.service.IOperationRecordService;
import com.ruoyi.bbsAdmin.service.RedisService;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.uuid.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.ruoyi.bbsAdmin.service.IContentService;

import javax.annotation.Resource;

/**
 * 内容帖Service业务层处理
 * 
 * @author ruoyi
 * @date 2022-04-01
 */
@Service
public class ContentServiceImpl implements IContentService 
{
    @Resource
    private ContentMapper contentMapper;

    @Resource
    private PlateMapper plateMapper;


    @Resource
    private bbs_userMapper userMapper;

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Autowired
    private RedisService redisService;

    @Autowired
    private IOperationRecordService operationRecordService;


    /**
     * 查询内容帖
     * 
     * @param contentid 内容帖主键
     * @return 内容帖
     */
    @Override
    public Content selectContentByContentid(String contentid)
    {
        return contentMapper.selectContentByContentid(contentid);
    }

    /**
     * 查询内容帖列表(弃用）
     * 
     * @param content 内容帖
     * @return 内容帖
     */
    @Override
    public List<Content> selectContentList(Content content)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        List<SysRole> roles = user.getRoles();
        Set<String> rolestrs = new HashSet<>();
        for (SysRole r:roles
        ) {
            rolestrs.add(r.getRoleKey());
        }
        if (rolestrs.contains("admin")){
            return contentMapper.selectContentList(content);
        }else {
            // 存在多个校园，sql
            List<String> schoolIds = new ArrayList<>();
            for (String rolestr: rolestrs
            ) {
                if (rolestr.contains("xygly")){
                    String schoolid = rolestr.replace("xygly","");
                    if (!"".equals(schoolid)){
                        schoolIds.add(rolestr.replace("xygly",""));
                    }

                }
            }
            return contentMapper.selectContentListByRole (content,schoolIds);

        }

    }

    /**
     * 查询内容帖列表
     *
     * @param ContentVo 内容帖+昵称
     * @return 内容帖+昵称
     */
    @Override
    public List<contentVo> selectContentVoList(contentVo ContentVo)
    {
//        List< contentVo> contentStructureList=new ArrayList<>();
//        if (ContentVo.getContenttype()==5 && ContentVo.getIsspecial()==0){
//            for(int i = 0; i < 5; i++){
//                ContentVo.setContenttype(i);
//                List< contentVo> contentList =contentMapper.selectContentVoList(ContentVo);
//
//            }
//        }
        List< contentVo> contentStructureList =contentMapper.selectContentVoList(ContentVo);
        if (contentStructureList.size()>0) {
            for (int i = 0; i < contentStructureList.size(); i++) {
                contentVo contentVo = contentStructureList.get(i);
                String userid = contentStructureList.get(i).getUserid();
                bbs_user user = userMapper.selectbbs_userByUserid(userid);
                String nickname = user.getNickname();
                if(nickname!=null) {
                    contentStructureList.get(i).setNickname(nickname);
                }
                if (user.getHeadimgurl()!=null){
                    contentStructureList.get(i).setHeadImgUrl(user.getHeadimgurl());
                }
                //处理匿名贴
                if (contentStructureList.get(i).getIsspecial() == 1 || contentStructureList.get(i).getIsspecial() == 4) { //匿名贴处理
                    contentVo = dealAnonymous(contentVo);
                    contentStructureList.get(i).setAnonymousName(contentVo.getAnonymousName());
                    contentStructureList.get(i).setHeadImgUrl(contentVo.getHeadImgUrl());
                }
            }
        }
        return contentStructureList;
    }

    @Override
    public List<contentVo> selectHotPostList(contentVo ContentVo) {
        List< contentVo> contentStructureList =contentMapper.selectHotPostList(ContentVo);
        if (contentStructureList.size()>0) {
            for (int i = 0; i < contentStructureList.size(); i++) {
                contentVo contentVo = contentStructureList.get(i);
                String userid = contentStructureList.get(i).getUserid();
                bbs_user user = userMapper.selectbbs_userByUserid(userid);
                String nickname = user.getNickname();
                if(nickname!=null) {
                    contentStructureList.get(i).setNickname(nickname);
                }
                if (user.getHeadimgurl()!=null){
                    contentStructureList.get(i).setHeadImgUrl(user.getHeadimgurl());
                }
                //处理匿名贴
                if (contentStructureList.get(i).getIsspecial() == 1 || contentStructureList.get(i).getIsspecial() == 4) { //匿名贴处理
                    contentVo = dealAnonymous(contentVo);
                    contentStructureList.get(i).setAnonymousName(contentVo.getAnonymousName());
                    contentStructureList.get(i).setHeadImgUrl(contentVo.getHeadImgUrl());
                }
            }
        }
        return contentStructureList;
    }

    private contentVo dealAnonymous(contentVo content) {
        //根据用户ID和帖子ID，生成该帖子下的唯一用户昵称
        //String newName = "隐士#";
        String newName = getChineseName(content.getContentid(), content.getUserid());
        String code = "";
        for (int j = 0; j < 7; j++) {
            if (j % 2 == 0) {
                code += content.getContentid().charAt(j);
            } else {
                code += content.getUserid().charAt(j);
            }
        }
//        newName = newName + content.getUserId().substring(0, 3);
//        content.setNickName(newName);
        //根据用户ID和帖子ID，生成该帖子下的唯一用户头像
        String regEx = "[^0-9]"; //提取所有数字
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(code);
        String num = m.replaceAll("").trim();
        //纯字符串处理
        if (num.equals("")) num = "0";
        int imageId = Integer.valueOf(num);
        imageId = imageId % 50;
        String headimgUrl = "https://image.tanxiaojian.zone/user/anonymous/" + String.valueOf(imageId) +
                ".png";
        if (content.getSchoolid()==9999){
            imageId = imageId % 34;
            headimgUrl = "https://image.tanxiaojian.zone/user/NXBAnonymous/" + String.valueOf(imageId) +
                    ".jpg";
        }
        content.setHeadImgUrl(headimgUrl);
        //设置昵称最后的编码
        Integer preNum = idToNum(content.getContentid());
        Integer sufNum = idToNum(content.getUserid());
        Integer total = preNum + sufNum;
        newName = newName + total;
        content.setAnonymousName(newName);
        return content;
    }

    public static String getChineseName(String contentId, String userId) {
        String result = "";
        Integer preNum = idToNum(contentId);
        Integer sufNum = idToNum(userId);
        Integer total = preNum + sufNum;
        //名称库
        String[] preName = new String[]{"赵", "钱", "孙", "李", "周", "吴", "郑", "王", "冯", "陈", "褚", "卫", "蒋", "沈", "韩", "杨", "朱", "秦", "尤", "许", "何", "吕", "施", "张", "孔", "曹", "严", "华", "金", "魏", "陶", "姜", "戚", "谢", "邹", "喻", "柏", "水", "窦", "章", "云", "苏", "潘", "葛", "奚", "范", "彭", "郎", "鲁", "韦", "昌", "马", "苗", "凤", "花", "方", "俞", "任", "袁", "柳", "酆", "鲍", "史", "唐", "费", "廉", "岑", "薛", "雷", "贺", "倪", "汤", "滕", "殷", "罗", "毕", "郝", "邬", "安", "常", "乐", "于", "时", "傅", "皮", "卞", "齐", "康", "伍", "余", "元", "卜", "顾", "孟", "平", "黄", "和", "穆", "萧", "尹", "姚", "邵", "湛", "汪", "祁", "毛", "禹", "狄", "米", "贝", "明", "臧", "计", "伏", "成", "戴", "谈", "宋", "茅", "庞", "熊", "纪", "舒", "屈", "项", "祝", "董", "梁", "杜", "阮", "蓝", "闵", "席", "季", "麻", "强", "贾", "路", "娄", "危", "江", "童", "颜", "郭", "梅", "盛", "林", "刁", "钟", "徐", "邱", "骆", "高", "夏", "蔡", "田", "樊", "胡", "凌", "霍", "虞", "万", "支", "柯", "昝", "管", "卢", "莫", "经", "房", "裘", "缪", "干", "解", "应", "宗", "丁", "宣", "贲", "邓", "郁", "单", "杭", "洪", "包", "诸", "左", "石", "崔", "吉", "钮", "龚", "程", "嵇", "邢", "滑", "裴", "陆", "荣", "翁", "荀", "羊", "於", "惠", "甄", "曲", "家", "封", "芮", "羿", "储", "靳", "汲", "邴", "糜", "松", "井", "段", "富", "巫", "乌", "焦", "巴", "弓", "牧", "隗", "山", "谷", "车", "侯", "宓", "蓬", "全", "郗", "班", "仰", "秋", "仲", "伊", "宫", "宁", "仇", "栾", "暴", "甘", "钭", "厉", "戎", "祖", "武", "符", "刘", "景", "詹", "束", "龙", "叶", "幸", "司", "韶", "郜", "黎", "蓟", "薄", "印", "宿", "白", "怀", "蒲", "邰", "从", "鄂", "索", "咸", "籍", "赖", "卓", "蔺", "屠", "蒙", "池", "乔", "阴", "鬱", "胥", "能", "苍", "双", "闻", "莘", "党", "翟", "谭", "贡", "劳", "逄", "姬", "申", "扶", "堵", "冉", "宰", "郦", "雍", "郤", "璩", "桑", "桂", "濮", "牛", "寿", "通", "边", "扈", "燕", "冀", "郏", "浦", "尚", "农", "温", "别", "庄", "晏", "柴", "瞿", "阎", "充", "慕", "连", "茹", "习", "宦", "艾", "鱼", "容", "向", "古", "易", "慎", "戈", "廖", "庾", "终", "暨", "居", "衡", "步", "都", "耿", "满", "弘", "匡", "国", "文", "寇", "广", "禄", "阙", "东", "欧", "殳", "沃", "利", "蔚", "越", "夔", "隆", "师", "巩", "厍", "聂", "晁", "勾", "敖", "融", "冷", "訾", "辛", "阚", "那", "简", "饶", "空", "曾", "毋", "沙", "乜", "养", "鞠", "须", "丰", "巢", "关", "蒯", "相", "查", "后", "荆", "红", "游", "竺", "权", "逯", "盖", "益", "桓", "公", "万", "俟", "司", "马", "上", "官", "欧", "阳", "夏", "侯", "诸", "葛", "闻", "人", "东", "方", "赫", "连", "皇", "甫", "尉", "迟", "公", "羊", "澹", "台", "公", "冶", "宗", "政", "濮", "阳", "淳", "于", "单", "于", "太", "叔", "申", "屠", "公", "孙", "仲", "孙", "轩", "辕", "令", "狐", "钟", "离", "宇", "文", "长", "孙", "慕", "容", "鲜", "于", "闾", "丘", "司", "徒", "司", "空", "丌", "官", "司", "寇", "仉", "督", "子", "车", "颛", "孙", "端", "木", "巫", "马", "公", "西", "漆", "雕", "乐", "正", "壤", "驷", "公", "良", "拓", "跋", "夹", "谷", "宰", "父", "谷", "梁", "晋", "楚", "闫", "法", "汝", "鄢", "涂", "钦", "段", "干", "百", "里", "东", "郭", "南", "门", "呼", "延", "归", "海", "羊", "舌", "微", "生", "岳", "帅", "缑", "亢", "况", "郈", "有", "琴", "梁", "丘", "左", "丘", "东", "门", "西", "门", "商", "牟", "佘", "佴", "伯", "赏", "南", "宫", "墨", "哈", "谯", "笪", "年", "爱", "阳", "佟", "第", "五", "言", "福", "百", "家", "姓", "诸葛"};
        String[] sufName = new String[]{"澄邈", "德泽", "海超", "海阳", "海荣", "海逸", "海昌", "瀚钰", "瀚文", "涵亮", "涵煦", "明宇", "涵衍", "浩皛", "浩波", "浩博", "浩初", "浩宕", "浩歌", "浩广", "浩邈", "浩气", "浩思", "浩言", "鸿宝", "鸿波", "鸿博", "鸿才", "鸿畅", "鸿畴", "鸿达", "鸿德", "鸿飞", "鸿风", "鸿福", "鸿光", "鸿晖", "鸿朗", "鸿文", "鸿轩", "鸿煊", "鸿骞", "鸿远", "鸿云", "鸿哲", "鸿祯", "鸿志", "鸿卓", "嘉澍", "光济", "澎湃", "彭泽", "鹏池", "鹏海", "浦和", "浦泽", "瑞渊", "越泽", "博耘", "德运", "辰宇", "辰皓", "辰钊", "辰铭", "辰锟", "辰阳", "辰韦", "辰良", "辰沛", "晨轩", "晨涛", "晨濡", "晨潍", "鸿振", "吉星", "铭晨", "起运", "运凡", "运凯", "运鹏", "运浩", "运诚", "运良", "运鸿", "运锋", "运盛", "运升", "运杰", "运珧", "运骏", "运凯", "运乾", "维运", "运晟", "运莱", "运华", "耘豪", "星爵", "星腾", "星睿", "星泽", "星鹏", "星然", "震轩", "震博", "康震", "震博", "振强", "振博", "振华", "振锐", "振凯", "振海", "振国", "振平", "昂然", "昂雄", "昂杰", "昂熙", "昌勋", "昌盛", "昌淼", "昌茂", "昌黎", "昌燎", "昌翰", "晨朗", "德明", "德昌", "德曜", "范明", "飞昂", "高旻", "晗日", "昊然", "昊天", "昊苍", "昊英", "昊宇", "昊嘉", "昊明", "昊伟", "昊硕", "昊磊", "昊东", "鸿晖", "鸿朗", "华晖", "金鹏", "晋鹏", "敬曦", "景明", "景天", "景浩", "俊晖", "君昊", "昆琦", "昆鹏", "昆纬", "昆宇", "昆锐", "昆卉", "昆峰", "昆颉", "昆谊", "昆皓", "昆鹏", "昆明", "昆杰", "昆雄", "昆纶", "鹏涛", "鹏煊", "曦晨", "曦之", "新曦", "旭彬", "旭尧", "旭鹏", "旭东", "旭炎", "炫明", "宣朗", "学智", "轩昂", "彦昌", "曜坤", "曜栋", "曜文", "曜曦", "曜灿", "曜瑞", "智伟", "智杰", "智刚", "智阳", "昌勋", "昌盛", "昌茂", "昌黎", "昌燎", "昌翰", "晨朗", "昂然", "昂雄", "昂杰", "昂熙", "范明", "飞昂", "高朗", "高旻", "德明", "德昌", "德曜", "智伟", "智杰", "智刚", "智阳", "瀚彭", "旭炎", "宣朗", "学智", "昊然", "昊天", "昊苍", "昊英", "昊宇", "昊嘉", "昊明", "昊伟", "鸿朗", "华晖", "金鹏", "晋鹏", "敬曦", "景明", "景天", "景浩", "景行", "景中", "景逸", "景彰", "昆鹏", "昆明", "昆杰", "昆雄", "昆纶", "鹏涛", "鹏煊", "景平", "俊晖", "君昊", "昆琦", "昆鹏", "昆纬", "昆宇", "昆锐", "昆卉", "昆峰", "昆颉", "昆谊", "轩昂", "彦昌", "曜坤", "曜文", "曜曦", "曜灿", "曜瑞", "曦晨", "曦之", "新曦", "鑫鹏", "旭彬", "旭尧", "旭鹏", "旭东", "浩轩", "浩瀚", "浩慨", "浩阔", "鸿熙", "鸿羲", "鸿禧", "鸿信", "泽洋", "泽雨", "哲瀚", "胤运", "佑运", "允晨", "运恒", "运发", "云天", "耘志", "耘涛", "振荣", "振翱", "中震", "子辰", "晗昱", "瀚玥", "瀚昂", "瀚彭", "景行", "景中", "景逸", "景彰", "绍晖", "文景", "曦哲", "永昌", "子昂", "智宇", "智晖", "晗日", "晗昱", "瀚昂", "昊硕", "昊磊", "昊东", "鸿晖", "绍晖", "文昂", "文景", "曦哲", "永昌", "子昂", "智宇", "智晖", "浩然", "鸿运", "辰龙", "运珹", "振宇", "高朗", "景平", "鑫鹏", "昌淼", "炫明", "昆皓", "曜栋", "文昂", "治汇", "恨桃", "依秋", "依波", "香巧", "紫萱", "涵易", "忆之", "幻巧", "美倩", "安寒", "白亦", "惜玉", "碧春", "怜雪", "听南", "念蕾", "紫夏", "凌旋", "芷梦", "凌寒", "梦竹", "千凡", "丹蓉", "慧贞", "思菱", "平卉", "笑柳", "雪卉", "南蓉", "谷梦", "巧兰", "绿蝶", "飞荷", "佳蕊", "芷荷", "怀瑶", "慕易", "若芹", "紫安", "曼冬", "寻巧", "雅昕", "尔槐", "以旋", "初夏", "依丝", "怜南", "傲菡", "谷蕊", "笑槐", "飞兰", "笑卉", "迎荷", "佳音", "梦君", "妙绿", "觅雪", "寒安", "沛凝", "白容", "乐蓉", "映安", "依云", "映冬", "凡雁", "梦秋", "梦凡", "秋巧", "若云", "元容", "怀蕾", "灵寒", "天薇", "翠安", "乐琴", "宛南", "怀蕊", "白风", "访波", "亦凝", "易绿", "夜南", "曼凡", "亦巧", "青易", "冰真", "白萱", "友安", "海之", "小蕊", "又琴", "天风", "若松", "盼菡", "秋荷", "香彤", "语梦", "惜蕊", "迎彤", "沛白", "雁彬", "易蓉", "雪晴", "诗珊", "春冬", "晴钰", "冰绿", "半梅", "笑容", "沛凝", "映秋", "盼烟", "晓凡", "涵雁", "问凝", "冬萱", "晓山", "雁蓉", "梦蕊", "山菡", "南莲", "飞双", "凝丝", "思萱", "怀梦", "雨梅", "冷霜", "向松", "迎丝", "迎梅", "雅彤", "香薇", "以山", "碧萱", "寒云", "向南", "书雁", "怀薇", "思菱", "忆文", "翠巧", "书文", "若山", "向秋", "凡白", "绮烟", "从蕾", "天曼", "又亦", "从语", "绮彤", "之玉", "凡梅", "依琴", "沛槐", "又槐", "元绿", "安珊", "夏之", "易槐", "宛亦", "白翠", "丹云", "问寒", "易文", "傲易", "青旋", "思真", "雨珍", "幻丝", "代梅", "盼曼", "妙之", "半双", "若翠", "初兰", "惜萍", "初之", "宛丝", "寄南", "小萍", "静珊", "千风", "天蓉", "雅青", "寄文", "涵菱", "香波", "青亦", "元菱", "翠彤", "春海", "惜珊", "向薇", "冬灵", "惜芹", "凌青", "谷芹", "雁桃", "映雁", "书兰", "盼香", "梅致", "寄风", "芳荷", "绮晴", "映之", "醉波", "幻莲", "晓昕", "傲柔", "寄容", "以珊", "紫雪", "芷容", "书琴", "美伊", "涵阳", "怀寒", "易云", "代秋", "惜梦", "宇涵", "谷槐", "怀莲", "英莲", "芷卉", "向彤", "新巧", "语海", "灵珊", "凝丹", "小蕾", "迎夏", "慕卉", "飞珍", "冰夏", "亦竹", "飞莲", "秋月", "元蝶", "春蕾", "怀绿", "尔容", "小玉", "幼南", "凡梦", "碧菡", "初晴", "宛秋", "傲旋", "新之", "凡儿", "夏真", "静枫", "芝萱", "恨蕊", "乐双", "念薇", "靖雁", "菊颂", "丹蝶", "元瑶", "冰蝶", "念波", "迎翠", "海瑶", "乐萱", "凌兰", "曼岚", "若枫", "傲薇", "雅芝", "乐蕊", "秋灵", "凤娇", "觅云", "依伊", "恨山", "从寒", "忆香", "香菱", "静曼", "青寒", "笑天", "涵蕾", "元柏", "代萱", "紫真", "千青", "雪珍", "寄琴", "绿蕊", "荷柳", "诗翠", "念瑶", "兰楠", "曼彤", "怀曼", "香巧", "采蓝", "芷天", "尔曼", "巧蕊", "八戒", "悟空", "金银", "珠宝", "伟鹏", "厚渡", "建国", "顾家", "一一", "依依", "不忙", "萌萌", "思思", "萱萱", "熙熙", "鹤轩", "伟祺", "祺祺", "鑫鑫", "明熙", "明旭", "文杰", "人杰", "明耀", "雄逸", "田磊", "天磊", "石磊", "俊哲", "修杰", "泽雨", "逸轩", "怡怿", "天佑", "德厚", "雅畅", "舒畅", "皓轩", "雅量", "泽铭", "泽民", "明远", "婉婷", "晏颖", "灵灵", "玉婷", "韵寒", "寒冰", "欣妍", "心祺", "佳琪", "诗诗", "诗涵", "菲林", "依娜", "雪莉", "茹雪", "灵慧", "灵芸", "芳菲", "澄泓", "彬彬", "佟伟", "炵伟", "彤彤", "浩然", "浩丽", "祺祺", "麒麒", "祁琪", "栖栖", "冉冉", "柒柒", "博雅"};
        result = sufName[((total % sufName.length))];
        return result+"#";
    }

    //提前id中的数字，生成整数
    public static Integer idToNum(String id) {
        Integer result = 0;
        String regEx = "[^0-9]"; //提取所有数字
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(id);
        String num = m.replaceAll("").trim();
        //纯字符串处理
        if (num.equals("")) num = "0";
        for (int i = 0; i < num.length(); i++) {
            result += Integer.parseInt(num.substring(i, i + 1));
        }
        return result;

    }

    @Override
    public List<Content> selectTreeContentList(treeSearchStructure treeSearchStructure) {
        Long schoolid = treeSearchStructure.getSchoolId();
        String plateid = treeSearchStructure.getPlateId();
        String cateid = treeSearchStructure.getCateId();
        Integer pageNum = treeSearchStructure.getPageNum();
        Integer pageSize = treeSearchStructure.getPageSize();
        System.out.println("pageSize是"+ pageSize);
        System.out.println("pageNum是"+ pageNum);
        //第一种模式，仅有schoolid，此时查询条件只有schoolid，点选学校级别
        QueryWrapper<Content> contentQueryWrapper = new QueryWrapper<>();
        if(schoolid!=null&&plateid==null&&cateid==null){
            contentQueryWrapper.eq("schoolId",schoolid);
        }
        //第二种模式，仅有schoolid和plateid，此时查询条件为plateid和schoolid，点选plate级别
        if(schoolid!=null&&plateid!=null&&cateid==null){
            contentQueryWrapper.eq("schoolId",schoolid);
            contentQueryWrapper.eq("plateId",plateid);
        }
        //第三种模式，仅有cateid和schoolid,点选分类级别
        if(schoolid!=null&&cateid!=null){
            QueryWrapper<Plate> plateQueryWrapper = new QueryWrapper<>();
            plateQueryWrapper.eq("cateId",cateid);
            plateQueryWrapper.eq("schoolId",schoolid);
            List<Plate> plateList = plateMapper.selectList(plateQueryWrapper);
            List<String> list = new ArrayList<String>();
            for (Plate item:plateList){
                list.add(item.getPlateid());
                System.out.println(item.getPlateid());
            }
            contentQueryWrapper.eq("schoolId",schoolid);
            if(list.size()!=0){
                contentQueryWrapper.in("plateId",list);
//                contentQueryWrapper.last("limit "+pageNum+','+pageSize);
//                if(pageNum==1){
//                    contentQueryWrapper.last("limit "+pageSize);
//                }else if(pageNum>1){
//                    contentQueryWrapper.last("limit "+ pageSize+","+pageNum);
//                }
//                contentQueryWrapper.last("limit "+ pageNum+","+pageSize);
            }
            else{
                return null;
            }
        }
        List<Content> contentList =contentMapper.selectList(contentQueryWrapper);
        System.out.println("条目数量为" + contentList.size());
        return contentList;
//        QueryWrapper<Plate> plateQueryWrapper = new QueryWrapper<>();
//        if(plateid==null){
//            if(cateid != null){
//                plateQueryWrapper.eq("cateId",cateid);
//            }
//            plateQueryWrapper.eq("schoolId",schoolid);
//            List<Plate> plateList = plateMapper.selectList(plateQueryWrapper);
//            List<String> list = new ArrayList<String>();
//            for (Plate item:plateList){
//                list.add(item.getPlateid());
//                System.out.println(item.getPlateid());
//            }
//            QueryWrapper<Content> contentQueryWrapper = new QueryWrapper<>();
//            contentQueryWrapper.eq("schoolId",schoolid);
//            if(list.size()>=1){
//                for(String item:list){
//                    contentQueryWrapper = contentQueryWrapper.eq("plateId",item).or();
//                }
//            }
//            return contentMapper.selectList(contentQueryWrapper);
//        }
//        else{
//            // 还是要做一个cate分类
//            QueryWrapper<Content> contentQueryWrapper = new QueryWrapper<>();
//            contentQueryWrapper.eq("schoolId",schoolid);
//            contentQueryWrapper.eq("plateId",plateid);
//            List<Content> contentList =contentMapper.selectList(contentQueryWrapper);
//            return contentList;
//        }

    }

//    @Override
//    public List<contentVo> selectTreeContentVoList(treeSearchStructure treeSearchStructure) {
//        Long schoolid = treeSearchStructure.getSchoolId();
//        String plateid = treeSearchStructure.getPlateId();
//        String cateid = treeSearchStructure.getCateId();
//        Integer pageNum = treeSearchStructure.getPageNum();
//        Integer pageSize = treeSearchStructure.getPageSize();
//        System.out.println("pageSize是"+ pageSize);
//        System.out.println("pageNum是"+ pageNum);
//        //第一种模式，仅有schoolid，此时查询条件只有schoolid，点选学校级别
//        QueryWrapper<Content> contentQueryWrapper = new QueryWrapper<>();
//        if(schoolid!=null&&plateid==null&&cateid==null){
//            contentQueryWrapper.eq("schoolId",schoolid);
//        }
//        //第二种模式，仅有schoolid和plateid，此时查询条件为plateid和schoolid，点选plate级别
//        if(schoolid!=null&&plateid!=null&&cateid==null){
//            contentQueryWrapper.eq("schoolId",schoolid);
//            contentQueryWrapper.eq("plateId",plateid);
//        }
//        //第三种模式，仅有cateid和schoolid,点选分类级别
//        if(schoolid!=null&&cateid!=null){
//            QueryWrapper<Plate> plateQueryWrapper = new QueryWrapper<>();
//            plateQueryWrapper.eq("cateId",cateid);
//            plateQueryWrapper.eq("schoolId",schoolid);
//            List<Plate> plateList = plateMapper.selectList(plateQueryWrapper);
//            List<String> list = new ArrayList<String>();
//            for (Plate item:plateList){
//                list.add(item.getPlateid());
//                System.out.println(item.getPlateid());
//            }
//            contentQueryWrapper.eq("schoolId",schoolid);
//            if(list.size()!=0){
//                contentQueryWrapper.in("plateId",list);
//            }
//            else{
//                return null;
//            }
//        }
//        List<Content> contentList =contentMapper.selectList(contentQueryWrapper);
////        List<contentVo> contentVoList =
////        System.out.println("条目数量为" + contentList.size());
//        return contentVoList;
//    }

    /**
     * 新增内容帖
     * 
     * @param content 内容帖
     * @return 结果
     */
    @Override
    public int insertContent(Content content)
    {

        String newUUID = UUID.randomUUID().toString().replace("-","");
        content.setContentid(newUUID);
        content.setUpnum(0);
        content.setDownnum(0);
        content.setForwardnum(0);
        content.setInformnum(0);
        content.setRealreadnum(0);
        content.setReadnum(0);
        content.setCommentnum(0);
        content.setNocomment(0);
        int result = contentMapper.insertContent(content);
        //在redis ZSet列表中添加该帖子
        int redisRes = redisService.addHomeContentToRedis(newUUID);
        return result;

    }

    /**
     * 修改内容帖
     * 
     * @param content 内容帖
     * @return 结果
     */
    @Override
    public int updateContent(Content content)
    {
        contentRedisVo oldContent = contentMapper.getContentVoById(content.getContentid());
        int result = contentMapper.updateContent(content);
        //在redis ZSet列表中修改该帖子的信息(更新对应帖子缓存)
        double timestamp = oldContent.getCreateTime().getTime();
        int redisRes = redisService.updateHomeContentInRedis(timestamp,content.getContentid());
        return result;
    }

    /**
     * 批量删除内容帖
     * 
     * @param contentids 需要删除的内容帖主键
     * @return 结果
     */
    @Override
    public int deleteContentByContentids(String[] contentids)
    {
        return contentMapper.deleteContentByContentids(contentids);
    }

    /**
     * 删除内容帖信息
     * 
     * @param contentid 内容帖主键
     * @return 结果
     */
    @Override
    public int deleteContentByContentid(String contentid)
    {
        return contentMapper.deleteContentByContentid(contentid);
    }

    //根据帖子ID删除redis中某个帖子缓存
    @Override
    public Boolean deletePostInRedisById(String contentId) {
        try{
            Object postInRedis= redisTemplate.opsForValue().get("getHomeContentVOById:" + contentId);
            if(postInRedis!=null) {
                redisTemplate.delete("getHomeContentVOById:" + contentId);
            }
            //同时更新长时间redis缓存中的帖子信息
            QueryWrapper<Content> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("contentId",contentId);
            Content content = contentMapper.selectOne(queryWrapper);
            //获取key前缀getHomeContents:加schoolId所有的key
            String str = "getHomeContents:"+content.getSchoolid();
            Set keys = redisTemplate.keys(str + "*");
            //删除相应的键值对
            if(keys.size()>0){
                redisTemplate.delete(keys);
            }
        } catch (Exception e) {
            System.out.println("redisError: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public Boolean deleteTopPostInRedis(int schoolId) {
        try{
            //删除该学校热榜redis缓存
//            Object hotPostInRedis= redisTemplate.opsForValue().get("getContentsPageByHot:" + schoolId + "---1-10-1");
//            if(hotPostInRedis!=null) {
//                redisTemplate.delete("getContentsPageByHot:" + schoolId + "---1-10-1");
//            }
            String strHot = "getContentsPageByHot:"+schoolId;
            Set keysHot = redisTemplate.keys(strHot + "*");
            //删除相应的键值对
            if(keysHot.size()>0){
                redisTemplate.delete(keysHot);
            }
            //删除该学校官方置顶帖的redis缓存
//            Object postInRedis= redisTemplate.opsForValue().get("getTopContents:" + schoolId + "--1-5");
//            if(postInRedis!=null) {
//                redisTemplate.delete("getTopContents:" + schoolId + "--1-5");
//            }
            String strTop = "getTopContents:"+schoolId;
            Set keysTop = redisTemplate.keys(strTop + "*");
            //删除相应的键值对
            if(keysTop.size()>0){
                redisTemplate.delete(keysTop);
            }

        } catch (Exception e) {
            System.out.println("redisError: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public Boolean deleteHomePostListInRedis(int schoolId) {
        try{
            //清除该学校首页帖子列表的redis缓存
            //获取key前缀getHomeContents:加schoolId所有的key
//            String str = "getHomeContents:"+schoolId;
//            Set keys = redisTemplate.keys(str + "*");
//            //删除相应的键值对
//            if(keys.size()>0){
//                redisTemplate.delete(keys);
//            }
//            //清除首页列表附带的前两条子评论的redis缓存
//            String strMC = "getMainCommentsByContentId:";
//            Set keysMC = redisTemplate.keys(strMC + "*");
//            //删除相应的键值对
//            if(keysMC.size()>0){
//                redisTemplate.delete(keysMC);
//            }
            //清除该学校首页评论缓存列表
            String strHomeContentList = "HomeContentVoList_" + schoolId;
            Set keysHomeContentList = redisTemplate.keys(strHomeContentList + "*");
            //删除相应的键值对
            if(keysHomeContentList.size()>0){
                redisTemplate.delete(keysHomeContentList);
            }
//            String setKey = "HomeContentVoList:" + schoolId + "-" + plateId + "-"  + contentType ;
            //拉取7天的帖子列表作为缓存
//            for (Object key: keysHomeContentList) {
//                String keyStr = String.valueOf(key);
//                String[] keyArray = keyStr.split("_");
//                String plateId = keyArray[2];
//                if (plateId.equals("NULL")){
//                    plateId ="";
//                }
//                int contentType = Integer.parseInt(keyArray[3]);
//                Date date = new Date();
//                SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                String queryTime = dateFormat.format(date);
//                redisService.addHomeContentToRedis("",plateId,schoolId,contentType,queryTime);
//
//            }
        } catch (Exception e) {
            System.out.println("redisError: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public Boolean updateHomePostListInRedis(int schoolId) {
        try{
            //设置为东八区
            SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
            Date date = new Date();
            String queryTime = dateFormat.format(date);
            //拉取7天的帖子列表作为缓存
            redisService.addOneWeekHomeContentToRedis(schoolId,queryTime);
        } catch (Exception e) {
            System.out.println("redisError: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public int changeAICheckContentState(int schoolId) {
        //下架一天内的所有匿名帖
        //设置为东八区
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        //获取前一天的起始时间
        Calendar calendar = Calendar.getInstance();//获取对日期操作的类对象
        calendar.add(Calendar.MINUTE, -30);//获取30分钟前的日期对象
        String thirtyMinutesAgo = dateFormat.format(calendar.getTime());//获取30分钟前的日期（带时分秒的）

        Calendar calendar2 = Calendar.getInstance();//获取对日期操作的类对象
        calendar2.add(Calendar.DATE, -1);//获取1天前前的日期对象
        String oneDayAgo = dateFormat.format(calendar2.getTime());//获取1天前的日期（带时分秒的）

        QueryWrapper<Content> contentQueryWrapper =new QueryWrapper<>();
        contentQueryWrapper.eq("schoolId",schoolId)
                .eq("contentState",13)
                .lt("createTime", thirtyMinutesAgo)
                .ge("createTime", oneDayAgo);
        List <Content> contentList = contentMapper.selectList(contentQueryWrapper);
        //加下帖子并创建下架操作记录
        for(Content content: contentList) {
            //更改帖子状态（0517改删除为私密）
            content.setContentstate(6);
            contentMapper.updateContent(content);
            //在缓存中贴子状态变为私密
            double timestampInRedis = content.getCreatetime().getTime();
            redisService.updateHomeContentInRedis(timestampInRedis,content.getContentid());
            //创建操作记录
            OperationRecord operationRecord =new OperationRecord();
            operationRecord.setSchoolId(schoolId);
            operationRecord.setRecordState(1);
            operationRecord.setOperator("ryTask");
            operationRecord.setTargetKind(2);
            operationRecord.setTargetId(content.getContentid());
            operationRecord.setNote("AI审核违规帖子下架");
            operationRecord.setChangeInfo("{\"data\":{\"oldForm\":{\"contentstate\":\"0\"},\"newForm\":{\"contentstate\":\"6\"}}}");
            operationRecordService.insertOperationRecord(operationRecord);
        }
        //下架广告并创建广告修改记录
        return 1;
    }

    @Override
    public List<contentVo> selectSAllSchoolContentVoList(contentVo ContentVo) {
        List< contentVo> contentStructureList =contentMapper.selectAllSchoolContentVoList(ContentVo);
        if (contentStructureList.size()>0) {
            for (int i = 0; i < contentStructureList.size(); i++) {
                String userid = contentStructureList.get(i).getUserid();
                bbs_user user = userMapper.selectbbs_userByUserid(userid);
                String nickname = user.getNickname();
                if(nickname!=null) {
                    contentStructureList.get(i).setNickname(nickname);
                }
                if (user.getHeadimgurl()!=null){
                    contentStructureList.get(i).setHeadImgUrl(user.getHeadimgurl());
                }
            }
        }
        return contentStructureList;
    }
}
